//
//  HDStatusDAL.swift
//  HDSwfitWeibo
//
//  Created by wty on 16/4/23.
//  Copyright © 2016年 wty. All rights reserved.
//

import UIKit

class HDStatusDAL: NSObject {
    //单例
    static let shareDAL :HDStatusDAL = HDStatusDAL()
    //缓存过期时间
    private let overTime :NSTimeInterval = 60*60
    private override init() {
        super.init()
    }
    //MARK - 0.加载数据  先从本地加载数据  如果没有就从网络加载数据
    func loadStatus(since_id :Int64,max_id:Int64,loadStatusCallback:(status:[[String:AnyObject]]? , error:NSError?)->()){
        //1.查看本地数据库是否保存数据
        loadCacheStatus(since_id, max_id: max_id) { (status, error) -> () in
            if status != nil && status!.count > 0 {
                //本地数据库有值 直接将数据的值回调出去
                loadStatusCallback(status: status, error: error)
            }
            return
        }
        //2.如果本地数据库没有数据就去网络架子啊数据
        //2.1.url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //2.2参数
        var parameters:[String:AnyObject] = ["access_token": HDUserAccoutViewModel.userAccoutShare.userAccount!.access_token!]
        if  since_id > 0{
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong:max_id-1)
        }

        //2.3.网络请求
        HDNetWorkTools.shareNetwork.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
            if let dict  = responseObject as? [String:AnyObject],let statusesDict = dict["statuses"] as?[[String:AnyObject]]{
              //保存到本地数据库
                self.saveCacheStatus(statusesDict )
              //将字典回调出去
                loadStatusCallback(status: statusesDict, error: nil)
            }

            }) { (task, error) -> Void in
                //将错误回调出去
                loadStatusCallback(status: nil, error: error)
                
        }
    }
    
    //MARK  -1.从本地加载数据
    private func  loadCacheStatus(since_id :Int64,max_id:Int64,loadCacheStatusCallback:(status:[[String:AnyObject]]? , error:NSError?)->()){
        //获取UID
        let uid = HDUserAccoutViewModel.userAccoutShare.userAccount?.uid
        //断言一定有
        assert(uid != nil,"没有id")
        //sql数据
        var sql = "SELECT status_id, status, user_id FROM T_Status \n" + "WHERE user_id = \(uid!) \n"
        if since_id > 0{
            //下拉刷新
            sql += "AND status_id > \(since_id)\n"
        }else if max_id > 0 {
            //上拉刷新
            sql += "AND status_id < \(max_id)\n"
        }
        sql += "ORDER DY status_id DESC LIMIT 20;"
        //查询数据
        HDSQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            do{
                let resultSet = try db.executeQuery(sql, values: [])
                //因为查找的是字符串 要把字符串 ->NSDate -> NSDict
                var  statusDicts = [[String:AnyObject]]()
                
                    while resultSet.next() {
                        let statusText = resultSet.stringForColumn("status")
                        let data = statusText.dataUsingEncoding(NSUTF8StringEncoding)!
                        let statusDict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String : AnyObject]
                        statusDicts.append(statusDict)
                    }
                //找到的字典数组回调出去给ViewModel  去字典转模型
                loadCacheStatusCallback(status: statusDicts, error: nil)
            }catch let error as NSError{
                //如果加载错误就回调错误出去
                loadCacheStatusCallback(status: nil, error: error)
                
            }
        }
        
    }
    
    //MARK  - 2.保存微博字典数组到数据库中
    private  func saveCacheStatus(statuses:[[String: AnyObject]]){
        //获取uid
        let uid  = HDUserAccoutViewModel.userAccoutShare.userAccount?.uid
        //断言
        assert(uid != nil, "没有uid")
        //sql语句
        let sql = "INSERT INTO T_Status (status_id,status,user_id) VALUES(?,?,?)"
        HDSQLiteManager.sharedManager.dbQueue.inTransaction { (db, rollBack) -> Void in
            do{
                //遍历获取每个字典  为了获取每个字典的id
                for dict in statuses{
                    let  id = dict["id"] as! NSNumber
                    //字典不能直接保存到数据库中  字典->NSData ->NSString
                    let data  = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
                    let statusText = String(data: data, encoding: NSUTF8StringEncoding)!
                    try db.executeUpdate(sql, values: [id,statusText,uid!])
                }
                HDPrint("保存了:\(statuses.count)条微博")
                
            }catch let error as NSError {
                HDPrint("保存微博出错:\(error)")
                
            }
       
          }
        }
    
    //MARK - 3.删除缓存
    func deleteCacheStatus(){
        //将过期时间转换成NSDate
        let date = NSDate(timeIntervalSinceNow: overTime)
        //转换成特定格式的字符串
        let df = NSDateFormatter()
        df.locale = NSLocale(localeIdentifier:"EN")
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let overString = df.stringFromDate(date)
        //sql 语句
        let sql = "DELETE FROM T_Status WHERE createTime < '\(overString)';"
        //执行sql语句
        HDSQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            do{
                try db.executeUpdate(sql, values: [])
            }catch let error as NSError {
                HDPrint("清除缓存失败\(error)")
            }
        }
    }
    

}
